

import { addHeaders } from "./funs/addHeaders";
import { IIsRequestSuccess, isRequestSuccess } from "./funs/isRequestSuccess";
import { IProcessDataOptions, processData } from "./funs/processData";
import { ISaveFileOptions, saveFile } from "./funs/saveFile";
import { setDomain } from "./funs/setDomain";
import { showError } from "./funs/showError";
import { addAuthorization } from "./funs/addAuthorization";
import { addCompanyId } from "./funs/addCompanyId";

/** 请求服务器 */
export const domain = import.meta.env.VITE_APP_DOMAIN;

/** 请求配置 */
export interface IOptions extends IProcessDataOptions, ISaveFileOptions, IIsRequestSuccess {

    /** 请求服务器 https://xxx.xxx.xxx */
    domain?: string;

    /** 是否显示错误提示 */
    isShowError?: boolean;
}

/**
 * 请求服务器
 * @param input 请求地址
 * @param init 请求配置
 * @param options 请求配置
 */
export async function fetch(input: RequestInfo | URL, init?: RequestInit | undefined, options?: IOptions) {
    try {
        // 设置请求域名
        let request = setDomain(input, init, domain, options);

        /** 添加默认头 */
        request = addHeaders(request.input, request.init);

        /** 添加授权 */
        request = addAuthorization(request.input, request.init);

        /** 添加公司 */
        request = addCompanyId(request.input, request.init);

        /** 返回数据 */
        let data = await window.fetch(request.input, request.init);

        // 校验通信是否成功
        data = await isRequestSuccess(data, options);

        // 保存文件
        data = await saveFile(data, options);

        // 提取业务数据
        return await processData(data, options);
    } catch (error) {
        throw showError(error, options);
    }
}

/** 请求错误 */
export class ServerError extends Error {

    /** 错误数据 */
    data: any;

    constructor(message: string, data: any) {
        super();
        this.message = message;
        this.data = data;
    }
}
